import { FileHelper } from './fileHelper'
import { TextHelper } from './textHelper'

/**
 * Provide functions to read a text file by lines
 */
export class TextFileReader {
	private lines: string[] = []

	private position: number = -1

	/**
	 * The current position
	 */
	public getPosition(): number {
		return this.position
	}

	public hasMore(steps: number = 0): boolean {
		return this.position + steps < this.lines.length - 1
	}

	public get length(): number {
		return this.lines.length
	}

	/**
	 * Move the position with steps
	 * @param steps the steps of the position move
	 */
	public move(steps: number = 1): void {
		this.position += steps
	}

	public open(path: string) {
		const content = FileHelper.readFileSync(path)
		this.lines = TextHelper.splitToLines(content)
		this.position = -1
	}

	/**
	 * Peak a line without position change.
	 * @param steps the steps relative to the current position.
	 */
	public peak(steps: number = 1): string | null {
		if (this.position + steps < this.length - 1) {
			return this.lines[this.position + steps]
		}
		return null
	}

	public read(): string | null {
		if (this.position < this.length - 1) {
			this.position += 1
			const line = this.lines[this.position]
			return line
		}
		return null
	}
}
